from handler_helpers.base_handler_helper import BaseHandlerHelper
from utils.check_params_utlil import CheckParams
from utils.handler_util import HandlerUtil


class ListHandlerHelper(BaseHandlerHelper):

    @staticmethod
    def _check_condition_data(data):
        for d in data:
            if not isinstance(d, dict):
                return False
            d_list = d.keys()
            if "field" not in d_list or "method" not in d_list or "value" not in d_list:
                return False
        return True

    def _get_verify_condition(self, conditions):
        if conditions and isinstance(conditions, dict):
            if "type" in conditions.keys() and "data" in conditions.keys():
                data = conditions['data']
                if isinstance(data, list):
                    _check_data = self._check_condition_data(data)
                    if _check_data:
                        return conditions
        return {}

    @property
    def _get_primary_key(self):
        if not hasattr(self.cls, "get_primary_key"):
            return "id"
        return self.cls().get_primary_key

    def list_handler(self, join_list=None, many_join_list=None, enum_list=None, has_is_delete=True):
        check_r = CheckParams(params=self.request.request_data,
                              conditions=[["conditions", False, {"data": [], "type": "and"}],
                                          ["page_num", False, 1],
                                          ["page_size", False, 10],
                                          ['order_by', False, self._get_primary_key],
                                          ['order_type', False, "desc"]]).check()
        if not check_r.is_success:
            return self.request.write(HandlerUtil.set_failure_response(message=check_r.message))
        conditions = self._get_verify_condition(check_r.data['conditions'])
        page_size = check_r.data['page_size']
        page_num = check_r.data['page_num']
        order_by = check_r.data['order_by']
        order_type = check_r.data['order_type']
        res = self.bll_cls(request=self.request, cls=self.cls).query_list(conditions, page_num, page_size, order_by,
                                                                          order_type, join_list, many_join_list,
                                                                          enum_list, has_is_delete)
        return self.request.write(HandlerUtil.set_success_response(data=res))
